﻿using System;
using System.IO;
using System.Linq;
using System.Web.Caching;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.CronJobs;
using Pap.Data.Abstraction.Utils;
using Pap.Services;
using Pap.Services.WorkflowEngine;

namespace Pap.Web.Utils.CronJobs
{
    /// <summary>
    /// 
    /// </summary>
    public class UnfreezeCronJob : ICronJob
    {
        /// <summary>
        /// Gets the sliding time.
        /// </summary>
        public TimeSpan SlidingTime
        {
            get
            {
                return TimeSpan.FromDays(1.0);
            }
        }
        /// <summary>
        /// Gets the name of the job.
        /// </summary>
        /// <value>
        /// The name of the job.
        /// </value>
        public string JobName
        {
            get
            {
                return "UnFreezeLoans";
            }
        }

        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (var uow = ServiceLocator.Current.GetInstance<IUnitOfWork>())
            {
                var wf = ServiceLocator.Current.GetInstance<IWorkflowService>();

                var stepInstances = wf.GetInstancesInStep(Steps.PostponeListWithResearchandStudy).Union(
                    wf.GetInstancesInStep(Steps.PostponeListWithoutResearchandStudy));

                stepInstances.ForEach(s =>
                                          {
                                              if (s.CompletionDate.HasValue && s.CompletionDate.Value.Date > DateTime.Today)
                                              {
                                                  wf.Move(ActionTypes.Unfreeze, s.ProcessInstanceID,
                                                          s.UserID.GetValueOrDefault(),
                                                          string.Empty, null);
                                              }
                                          });
                uow.Commit();
            }
        }
    }
}
